package com.ailesson.video.listener;

import cn.hutool.core.collection.CollectionUtil;
import com.ailesson.video.entity.SubjectEntity;
import com.ailesson.video.model.dto.ExcErrorInfoDto;
import com.ailesson.video.model.dto.SubjectExcDto;
import com.ailesson.video.service.SubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


@Slf4j
public class ReadExcelListener implements ReadListener<SubjectExcDto> {

    private int batchCount;

    //缓存对象，达到最大数量，需要存库，清空缓存
    private List<SubjectEntity> cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);

    private SubjectService subjectService;

    private List<ExcErrorInfoDto> errorInfoDtos;


    public ReadExcelListener(Integer batchCount,SubjectService subjectService,List<ExcErrorInfoDto> errorInfoDtos) {
        this.batchCount = batchCount;
        this.subjectService = subjectService;
        this.errorInfoDtos = errorInfoDtos;
    }

    @Override
    public void invoke(SubjectExcDto subjectExcDto, AnalysisContext analysisContext) {
        int i = 0;
        if (subjectExcDto.getId() == null || subjectExcDto.getId() <= 0){
            errorInfoDtos.add(new ExcErrorInfoDto("id","ID不能为空或小于等于0"));
            i++;
        }else{
            long count = subjectService.count(new LambdaQueryWrapper<SubjectEntity>()
                    .eq(SubjectEntity::getId, subjectExcDto.getId()));
            if (count > 0){
                errorInfoDtos.add(new ExcErrorInfoDto("id","ID:["+subjectExcDto.getId()+"]已经存在，请使用其他ID"));
                i++;
            }
        }
        if (!StringUtils.hasText(subjectExcDto.getTitle())){
            errorInfoDtos.add(new ExcErrorInfoDto("title","课程分类不能为空"));
            i++;
        }
        if (subjectExcDto.getParentId() != null && subjectExcDto.getParentId() != 0){
            long count = subjectService.count(new LambdaQueryWrapper<SubjectEntity>()
                    .eq(SubjectEntity::getId, subjectExcDto.getParentId()));
            if (count == 0){
                errorInfoDtos.add(new ExcErrorInfoDto("parentId","上级ID:["+subjectExcDto.getParentId()+"]不存在，请先添加上级ID"));
                i++;
            }
        }
        if (i == 0){
            SubjectEntity entity = new SubjectEntity();
            BeanUtils.copyProperties(subjectExcDto,entity);
            cachedDataList.add(entity);
            if (cachedDataList.size() >= batchCount){
                subjectService.saveBatch(cachedDataList,batchCount);
                // 存储完成清理 list
                cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollectionUtil.isNotEmpty(cachedDataList)){
            subjectService.saveBatch(cachedDataList);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("课程导入错误：{}",exception);
        Map<Integer, Head> headMap = context.currentReadHolder().excelReadHeadProperty().getHeadMap();
        if (CollectionUtil.isNotEmpty(headMap)){
            Head head = headMap.get(context.currentReadHolder().excelReadHeadProperty().getHeadRowNumber());
            if (head != null){
                errorInfoDtos.add(new ExcErrorInfoDto(head.getFieldName(),head.getHeadNameList().get(0)+"错误:"+exception.getMessage()));
            }
        }

    }
}
